//
//  TOrderInfoDAL.m
//  CarSalesMS_GCX
//
//  Created by Ssky on 2016/11/10.
//  Copyright © 2016年 Tony. All rights reserved.
//

#import "TOrderInfoDAL.h"
#import "TOrderInfoModel.h"
#import "TSaleInfoModel.h"

@implementation TOrderInfoDAL


+ (TOrderInfoModel *)loadOrderModelWithDict:(NSDictionary *)dict {
    TOrderInfoModel * model = [[TOrderInfoModel alloc] init];
    model.orId = [dict[@"orId"] intValue];
    model.orOrderNo = dict[@"orOrderNo"];
    model.orCount = dict[@"orCount"];
    model.orTotalCount = [dict[@"orTotalCount"] intValue];
    model.orUnitMoney = dict[@"orUnitMoney"];
    model.orTotalMoney = [dict[@"orTotalMoney"] floatValue];
    model.orWarehouseNo = dict[@"orWarehouseNo"];
    model.orSalesmanNo = dict[@"orSalesmanNo"];
    model.orSalesman = dict[@"orSalesman"];
    model.orBusinessmanNo = dict[@"orBusinessmanNo"];
    model.orBusinessman = dict[@"orBusinessman"];
    model.orSaleType = [dict[@"orSaleType"] intValue];
    model.orSettlementType = [dict[@"orSettlementType"] intValue];
    model.orState = [dict[@"orState"] intValue];
    model.orCreateTime = dict[@"orCreateTime"];
    model.orDashedTime = dict[@"orDashedTime"];
    model.orRemark = dict[@"orRemark"];
    
    return model;
}

+ (NSArray<TOrderInfoModel *> *)loadModelListWithSql:(NSString *)sql {
    //
    NSMutableArray<TOrderInfoModel *> *mArr = [NSMutableArray<TOrderInfoModel *> array];
    
    NSArray<NSDictionary *> *arr = [[CSFMDBTool SharedFmdbTool] loadDataWithSql:sql];
    for (NSDictionary *dict in arr) {
        [mArr addObject:[self loadOrderModelWithDict:dict]];
    }
    return mArr.copy;
}

+ (NSString *)loadOrderNoLast {
    NSString * sql = @"select * from tOrderInfo order by orCreateTime desc limit 0,1; ";
    
    return [self loadOrderModelWithDict:[[CSFMDBTool SharedFmdbTool] loadDataWithSql:sql][0]].orOrderNo;
}

+ (NSArray<TOrderInfoModel *> *)loadOrderListWithOrderNo:(NSString *)orderNo {
    NSString * sql = [NSString stringWithFormat:@"select * from tOrderInfo where orOrderNo='%@'; ", orderNo];
    
    return [self loadModelListWithSql:sql];
}

+ (TOrderInfoModel *)loadOrderModelWithOrderNo:(NSString *)orderNo {
    return [self loadOrderListWithOrderNo:orderNo][0];
}

+ (TOrderInfoModel *)loadOrderModelTopOneOrderByTimeDescWithTime:(NSString *)time {
    NSString * sql = [NSString stringWithFormat:@"select * from tOrderInfo where orCreateTime>'%@' order by orCreateTime desc limit 0,1; ", time];
    
    NSArray<NSDictionary *> * arr = [[CSFMDBTool SharedFmdbTool] loadDataWithSql:sql];
    if (arr.count == 0) {
        return nil;
    }
    return [self loadOrderModelWithDict:arr[0]];
}

+ (TOrderInfoModel *)getOrderInfoModelWithOrderNo:(NSString *)orderNo totalCount:(int)totalCount totalMoney:(CGFloat)totalMoney unitCount:(NSString *)unitCount unitMoney:(NSString *)unitMoney saleModel:(TSaleInfoModel *)saleM {
    //
    TOrderInfoModel * model = [[TOrderInfoModel alloc] init];
    //    model.orId = saleM.;
    model.orOrderNo = orderNo;
    model.orCount = unitCount;
    model.orTotalCount = totalCount;
    model.orUnitMoney = unitMoney;
    model.orTotalMoney = totalMoney;
    model.orWarehouseNo = saleM.sWarehouseNo;
    model.orSalesmanNo = saleM.sSalesmanNo;
    model.orSalesman = saleM.sSalesman;
    model.orBusinessmanNo = saleM.sBusinessmanNo;
    model.orBusinessman = saleM.sBusinessman;
    model.orSaleType = saleM.sSaleType;
    model.orSettlementType = saleM.sSettlementType;
    model.orState = 0;
    model.orCreateTime = [[CSGXDateFormatterManager sharedManager] currentTime];
    
    model.orRemark = saleM.sRemark;
    
    
    return model;
}

+ (NSArray<TOrderInfoModel *> *)loadOrderListWithTimeBegin:(NSString *)timeBegin timeEnd:(NSString *)timeEnd {
    // 从开始日期的零点到结束日期的下一天的零点。
    timeBegin = [timeBegin stringByAppendingString:@" 00:00:00"];
    
    int timeEndN = [[timeEnd subStringBackOfLastIndex:2] intValue];
    timeEnd = [[timeEnd subStringFrontOfLastIndex:2] stringByAppendingFormat:@"%d 00:00:00", (timeEndN + 1)];
    
    NSString * sql = [NSString stringWithFormat:@"select * from tOrderInfo where orCreateTime between '%@' and '%@' order by orCreateTime desc; ", timeBegin, timeEnd];
    
    //    NSLog(@"%@", sql);
    return [self loadModelListWithSql:sql];
}






#pragma mark - insert
+ (NSArray *)insertIntoDbWithOrderList:(NSArray<TOrderInfoModel *> *)orderList {
    
    NSMutableArray<NSNumber *> * insertIdsM = [NSMutableArray array];
    NSInteger lastId = 0;
    for (TOrderInfoModel *model in orderList) {
        lastId = [self insertIntoDbWithOrderModel:model];
        [insertIdsM addObject:@(lastId)];
    }
    return insertIdsM.copy;
}


+ (NSInteger)insertIntoDbWithOrderModel:(TOrderInfoModel *)orderModel {
    NSString * sql = [NSString stringWithFormat:@"INSERT INTO tOrderInfo ("
                      "orOrderNo,"
                      "orCount,"
                      "orTotalCount,"
                      "orUnitMoney,"
                      "orTotalMoney, "
                      "orWarehouseNo, "
                      "orSalesmanNo, "
                      "orSalesman, "
                      "orBusinessmanNo, "
                      "orBusinessman, "
                      "orSaleType, "
                      "orSettlementType, "
                      "orState, "
                      "orCreateTime, "
                      "orDashedTime, "
                      "orRemark"
                      ")"
                      "VALUES ('%@', '%@', %d, '%@', %.2f, '%@', '%@', '%@', '%@', '%@', %d, %d, %d, '%@', '%@', '%@'); ",
                      orderModel.orOrderNo,
                      orderModel.orCount,
                      orderModel.orTotalCount,
                      orderModel.orUnitMoney,
                      orderModel.orTotalMoney,
                      orderModel.orWarehouseNo,
                      orderModel.orSalesmanNo,
                      orderModel.orSalesman,
                      orderModel.orBusinessmanNo,
                      orderModel.orBusinessman,
                      orderModel.orSaleType,
                      orderModel.orSettlementType,
                      orderModel.orState,
                      orderModel.orCreateTime,
                      orderModel.orDashedTime,
                      orderModel.orRemark];
    
    return [[CSFMDBTool SharedFmdbTool] updateTableWithSql:sql];
}


#pragma mark - update
+ (void)updateOrderModelWithSql:(NSString *)sql {
    [[CSFMDBTool SharedFmdbTool] updateTableWithSql:sql];
}

+ (void)updateOrderModel:(TOrderInfoModel *)orderModel {
    NSString * sql = [NSString stringWithFormat:@"update tOrderInfo set "
                      "orOrderNo = '%@', "
                      "orCount = '%@', "
                      "orTotalCount = %d, "
                      "orUnitMoney = '%@', "
                      "orTotalMoney = %.2f, "
                      "orWarehouseNo = '%@', "
                      "orSalesmanNo = '%@', "
                      "orSalesman = '%@', "
                      "orBusinessmanNo = '%@', "
                      "orBusinessman = '%@', "
                      "orSaleType = %d, "
                      "orSettlementType = %d, "
                      "orState = %d, "
                      "orCreateTime = '%@', "
                      "orDashedTime = '%@', "
                      "orRemark = '%@' "
                      " where orId = %d; ",
                      
                      orderModel.orOrderNo,
                      orderModel.orCount,
                      orderModel.orTotalCount,
                      orderModel.orUnitMoney,
                      orderModel.orTotalMoney,
                      orderModel.orWarehouseNo,
                      orderModel.orSalesmanNo,
                      orderModel.orSalesman,
                      orderModel.orBusinessmanNo,
                      orderModel.orBusinessman,
                      orderModel.orSaleType,
                      orderModel.orSettlementType,
                      orderModel.orState,
                      orderModel.orCreateTime,
                      orderModel.orDashedTime,
                      orderModel.orRemark,
                      orderModel.orId
                      ];
    [self updateOrderModelWithSql:sql];
}

+ (void)updateOrderList:(NSArray<TOrderInfoModel *> *)orderList {
    for (TOrderInfoModel *model in orderList) {
        [self updateOrderModel:model];
    }
}

+ (void)updateOrderModel:(TOrderInfoModel *)orderModel withOrderNo:(NSString *)orderNo {
    NSString * sql = [NSString stringWithFormat:@"update tOrderInfo set "
                      
                      "orTotalPrice = %.2f, "
                      "orState = %d, "
                      "orRemark = '%@' "
                      " where orOrderNo = '%@'; ",
                      
                      orderModel.orTotalMoney,
                      orderModel.orState,
                      orderModel.orRemark,
                      orderModel.orOrderNo
                      ];
    [self updateOrderModelWithSql:sql];
}


#pragma mark - create new orderModel
///生成新订单
+ (TOrderInfoModel *)getOrderModelWithOrderNo:(NSString *)orderNo saleList:(NSArray<TSaleInfoModel *> *)saleModelList {
    //
    NSMutableArray<NSNumber *> *countArrM = [NSMutableArray<NSNumber *> arrayWithArray:@[@(0),@(0),@(0)]];
    NSMutableArray<NSNumber *> *moneyArrM = [NSMutableArray<NSNumber *> arrayWithArray:@[@(0),@(0),@(0)]];
    NSString *unitCount = @"";
    NSString *unitMoney = @"";
    CGFloat totalCountF = 0;
    CGFloat totalMoneyF = 0;
    
    // 循环完善saleList并入库；计算order中的总数量和总价钱
    for (int i = 0; i < saleModelList.count; i++) {
        totalMoneyF += saleModelList[i].sTotalMoney;
        
        NSArray *unitMoneyArr = [saleModelList[i].sUnitMoney componentsSeparatedByString:@","];
        NSArray *unitCountArr = [saleModelList[i].sCount componentsSeparatedByString:@","];
        
        for (int j = 0; j < unitCountArr.count; j++) {
            
            // 如果是第一个，那么都改变；如果只有两个单位，那么第二个单位为小单位，加到第三个位置；如果有三个单位，那么对应加入。
            if (j == 0) {
                countArrM[j] = @([countArrM[j] intValue] + [unitCountArr[j] intValue]);
                moneyArrM[j] = @([moneyArrM[j] floatValue] + [unitMoneyArr[j] floatValue]);
                continue;
            }
            
            if (unitCountArr.count == 2) {
                countArrM[j + 1] = @([countArrM[j + 1] intValue] + [unitCountArr[j] intValue]);
                moneyArrM[j + 1] = @([moneyArrM[j + 1] floatValue] + [unitMoneyArr[j] floatValue]);
            }else if (unitCountArr.count == 3) {
                countArrM[j] = @([countArrM[j] intValue] + [unitCountArr[j] intValue]);
                moneyArrM[j] = @([moneyArrM[j] floatValue] + [unitMoneyArr[j] floatValue]);
            }
        }
        
        saleModelList[i].sOrderNo = orderNo;
        saleModelList[i].sWarehouseNo = [CSUserDefaultsTool getWarehouseNo];
        saleModelList[i].sWarehouseName = [CSUserDefaultsTool getWarehouse];
        saleModelList[i].sSalesmanNo = [CSUserDefaultsTool getUserNo];
        saleModelList[i].sSalesman = [CSUserDefaultsTool getUserName];
        saleModelList[i].sBusinessmanNo = [CSUserDefaultsTool getBusinessmanNo];
        saleModelList[i].sBusinessman = [CSUserDefaultsTool getBusinessman];
        saleModelList[i].sCreateTime = [[CSGXDateFormatterManager sharedManager] currentTime];
    }
    
    for (int i = 0; i < countArrM.count; i++) {
        totalCountF += [countArrM[i] intValue];
        unitCount = [unitCount stringByAppendingFormat:@"%@,", countArrM[i]];
        unitMoney = [unitMoney stringByAppendingFormat:@"%@,", moneyArrM[i]];
    }
    
    unitCount = [unitCount subStringFrontOfLastIndex:1];
    unitMoney = [unitMoney subStringFrontOfLastIndex:1];
    
    TOrderInfoModel * orderModel = [self getOrderInfoModelWithOrderNo:orderNo totalCount:totalCountF totalMoney:totalMoneyF unitCount:unitCount unitMoney:unitMoney saleModel:saleModelList[0]];
    
    return orderModel;
}


+ (NSString *)getOrderNoStr {
    
    NSString * todyTime = [[CSGXDateFormatterManager sharedManager] currentTime];
    NSString * userNo = [CSUserDefaultsTool getUserNo];
    
    NSString * orderNoStr = [NSString stringWithFormat:@"%@%@", userNo,
                             [[[todyTime stringByReplacingOccurrencesOfString:@"-" withString:@""]
                               stringByReplacingOccurrencesOfString:@":" withString:@""]
                              stringByReplacingOccurrencesOfString:@" " withString:@""]];
    [CSUserDefaultsTool setOrderNo:orderNoStr];
    return orderNoStr;
}







@end
